//
// Created by ziya on 22-8-23.
//

/**
 *  模拟CPU的时钟中断
 */
#include "../../include/common.h"
#include <pthread.h>
#include <signal.h>

// 时钟频率 300ms
#define CLOCK_RATE  400000

static pthread_mutex_t mutex;
static pthread_cond_t cond;

void* thread_fun(void* arg) {
    INFO_PRINT("模拟CPU时钟中断准备就绪\n");

    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);
    pthread_mutex_unlock(&mutex);

    INFO_PRINT("开始调度\n");

    while (true) {
        kill(getpid(), SIGUSR1);

        usleep(CLOCK_RATE);
    }
}

void cpu_init() {
    pthread_t tid;

    // 初始化
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    // 以分离形态创建线程
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    pthread_create(&tid, &attr, thread_fun, NULL);

    // 销毁attr
    pthread_attr_destroy(&attr);
}

/**
 *  模拟启用时钟中断
 */
void start_cpu() {
    pthread_cond_broadcast(&cond);
}